package com.hzit.servlet;

import cn.hutool.core.util.StrUtil;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzit.entity.PageResult;
import com.hzit.entity.R;
import com.hzit.entity.Student;
import com.hzit.service.IStudentService;
import com.hzit.util.ResponseUtil;
import com.hzit.vo.StudentVo;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Service;
import java.io.IOException;

import static jdk.nashorn.internal.objects.NativeString.search;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private IStudentService studentService;

	//1. 在servlet开始加载时调用此方法，从spring容器中得到IStudentService对象
	@Override
	public void init() throws ServletException {
		//在servlet容器中得到spring容器：
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		//从spring容器中得到IStudentService
		studentService = wac.getBean(IStudentService.class);
	}

	//2. 每次请求都要调用此方法
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json;charset=utf8");
		//2.1 得到请求参数
		String cmd = req.getParameter("cmd");
		//2.2 根据请求参数的值，决定调用哪个方法
		if (StrUtil.isNotBlank(cmd)) {
			if ("list".equals(cmd)) {
				list(req, resp);                             // 列表学生
			}
			if ("search".equals(cmd)) {
				search(req, resp);                           // 条件查询带分页
			}
		}
	}

	private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 得到分页参数
		int page = new Integer(req.getParameter("page"));               // 当前页
		int pageSize = new Integer(req.getParameter("pageSize"));       // 每页大小
		//2. 得到分页中查询条件对象
		ObjectMapper ObjectMapper = new ObjectMapper();
		StudentVo studentVo = ObjectMapper.readValue(req.getInputStream(), StudentVo.class);
		try {
			//3. 开始查询
			PageResult<Student> pr = studentService.search(page,pageSize,studentVo);
			//4. 输出内容到前端
			ResponseUtil.out(resp, R.ok(pr));
		} catch (Exception e) {
			e.printStackTrace();
			//5. 当查询失败时，就跳转到这里输出错误信息到页面
			ResponseUtil.out(resp, R.fail("条件带分页查询失败！"));
		}
	}

	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	}
}
